package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Mylinja 2021-12-21 星期二 17:18
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车方法
     *
     * @param shoppingCart 用户传递的菜品或套餐信息
     * @return 返回添加到购物车的对象
     */
    @PostMapping("/add")
    public R<ShoppingCart> addCart(@RequestBody ShoppingCart shoppingCart) {
        log.info("购物车数据：{}", shoppingCart);

        ShoppingCart cartServiceOne = shoppingCartService.addCart(shoppingCart);
        return R.success(cartServiceOne);
    }

    /**
     * 查询购物车
     *
     * @return 返回成功结果
     */
    @GetMapping("/list")
    @SuppressWarnings({"unchecked", "varargs"})
    public R<List<ShoppingCart>> list() {
        log.info("查看购物车");

        // SQL: select * from shoppingCart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> query = new LambdaQueryWrapper<>();
        query.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        query.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(query);
        return R.success(list);
    }

    /**
     * 清空购物车
     *
     * @return 返回成功结果
     */
    @DeleteMapping("/clean")
    public R<String> clean() {
        log.info("清空购物车。。。");

        //SQL: delete from ShoppingCart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> query = new LambdaQueryWrapper<>();
        query.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        shoppingCartService.remove(query);
        return R.success("清空购物车成功");
    }

    /**
     * 删除一条购物车里面的条目
     *
     * @param shoppingCart 用来封装setmealId
     * @return 返回购物车对象
     */
    @PostMapping("/sub")
    public R<ShoppingCart> deleteOne(@RequestBody ShoppingCart shoppingCart) {
        log.info("删除购物车中的一个条目");

        ShoppingCart cart = shoppingCartService.deleteInShoppingCart(shoppingCart);
        return R.success(cart);
    }
}
